from flask import Flask, flash, jsonify, Response, render_template, request, session, redirect, url_for
import simplejson as json
from flask_session import Session
from apps.admin import app, db

from random import randint
import random
from captcha.image import ImageCaptcha
from apps.admin.util.common import generate_captcha_image
import io


# 调用验证码图片生成接口
@app.route('/get_captcha')
def get_captcha():
    # image = ImageCaptcha().generate_image("9527")
    # return image.show()

    # response = make_response(image)
    # # 设置请求头属性-Content-Type响应的格式
    # response.headers["Content-Type"] = "image/png"
    # return response

    # 使用上述函数生成验证码图片
    image, captcha_text = generate_captcha_image()

    # 将验证码文本存储到session，以便之后进行验证
    session['captcha'] = captcha_text

    buf = io.BytesIO()
    image.save(buf, format='PNG')
    buf.seek(0)
    return buf.getvalue(), 200, {
        'Content-Type': 'image/png',
        'Content-Length': str(len(buf.getvalue()))
    }
